#include <stdio.h>
#include <stdlib.h>
#include "list.h"

int sll_insert_by_location(slink *list, int i, int data){
    if(i < 1 ){
        printf("invialed location i\n");
        return -1;
    }

    if(i == 1){
        sllnode *new = (sllnode *)malloc(sizeof(sllnode));
        if(new == NULL){
            perror("malloc");
            return -1;
        }

        new->data = data;
        new->next = *list;
        *list = new;
        return 0;
    }

    sllnode *s = *list;
    int j = 0;
    while(s != NULL && j < i-2){
        s = s->next;
        j++;
    }
    if(s == NULL){
        printf("location  i  is enpty\n");
        return -1;
    }
        

    sllnode *l = (sllnode *)malloc(sizeof(sllnode));
    if(l == NULL){
            perror("malloc");
            return -1;
        }
    l->data = data;
    l->next = s->next;
    s->next = l;

    return 0;
}

int sll_delete_by_location(slink *list, int i){
    if(i < 1 || *list == NULL){
        printf("invalied location i or list is empty\n");
        return -1;
    }
    
    sllnode *q = *list;
    if(i == 1){
        *list = q->next;
        free(q);
        return 0;
    }

    sllnode *l = *list;
    int j = 0;
    while(l != NULL && j < i-2){
        l = l->next;
        j++;
    }

    if(l == NULL || l->next == NULL){
        printf("nothing to delete\n");
        return -1;
    }
    
    sllnode *p = l->next;
    l->next = p->next;
    free(p);

    return 0;
}

sllnode *sll_find_node_by_location(slink *list, int i){
    if(i < 1 || *list == NULL){
        printf("invalied location or list empty\n");
        return NULL;
    }

    sllnode *p = *list;
    int j = 0;
    while(p != NULL && j < i-1){
        p = p->next;
        j++;
    }

    if(p == NULL){
        printf("no sllnode %d in list\n",i);
        return NULL;
    }
    
    return p;
}

sllnode *sll_find_node_by_data(slink *list, int data, int *location){
    if(*list == NULL){
        printf("list is empty\n");
        return NULL;
    }

    sllnode *p = *list;
    int i = 1;
    while (p != NULL)
    {
        if(p->data == data)
            break;
        p = p->next;
        i++;
    }

    if(p == NULL){
        printf("no sllnode with data %d\n",data);
        return NULL;
    }

    *location = i;

    return p; 
}

int sll_length_of_list(slink *list){
    if(*list == NULL)
        return 0;
    
    int i = 0;
    sllnode *p = *list;
    while(p != NULL){
        p = p->next;
        i++;
    }

    return i;
}